/**
 * 
 */
package travibot.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import org.apache.log4j.Logger;
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

/**
 * @author tajzivit
 * 
 */
public class GenericParser implements Parser {   

    private static Logger log = Logger.getLogger(GenericParser.class);

    private Document document;

    public Document getDocument() {

        return this.document;
    }
    
    public void parse(Parser.ParserType parserType, InputStream inputStream) {
        log.info("Parsing of the stream of Type " + parserType + " has started");
        DOMParser domParser = new DOMParser();
        try {
            domParser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
            domParser.parse(new InputSource(inputStream));
        }
        catch (SAXNotRecognizedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SAXNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        document = domParser.getDocument();                
    }   

    /**
     * prints document to console
     * 
     */
    public void printDocument() {

        printDocument(document, "    ");
    }

    /**
     * Prints document to Console
     * 
     * @param node
     *            start node
     * @param indent
     *            string representation of indent
     */
    private void printDocument(Node node, String indent) {

        System.out.println(indent + node.getNodeName());
        Node child = node.getFirstChild();
        while (child != null) {
            printDocument(child, indent + " ");
            child = child.getNextSibling();
        }
    }
}
